#!/usr/bin/env python3
"""
笔记路由
"""

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from models import db, Note

bp = Blueprint('notes', __name__)

@bp.route('/', methods=['GET'])
@jwt_required()
def get_notes():
    """获取当前用户的所有笔记"""
    try:
        current_user_id = int(get_jwt_identity())
        notes = Note.query.filter_by(user_id=current_user_id).order_by(Note.updated_at.desc()).all()
        
        return jsonify({
            'notes': [note.to_dict() for note in notes]
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@bp.route('/', methods=['POST'])
@jwt_required()
def create_note():
    """创建新笔记"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        if not data or not data.get('title'):
            return jsonify({'error': '标题不能为空'}), 400
        
        note = Note(
            user_id=current_user_id,
            title=data['title'],
            content=data.get('content', '')
        )
        
        db.session.add(note)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'note': note.to_dict()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


@bp.route('/<int:note_id>', methods=['GET'])
@jwt_required()
def get_note(note_id):
    """获取单个笔记"""
    try:
        current_user_id = int(get_jwt_identity())
        note = Note.query.filter_by(id=note_id, user_id=current_user_id).first()
        
        if not note:
            return jsonify({'error': '笔记不存在'}), 404
        
        return jsonify({
            'note': note.to_dict()
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@bp.route('/<int:note_id>', methods=['PUT'])
@jwt_required()
def update_note(note_id):
    """更新笔记"""
    try:
        current_user_id = int(get_jwt_identity())
        note = Note.query.filter_by(id=note_id, user_id=current_user_id).first()
        
        if not note:
            return jsonify({'error': '笔记不存在'}), 404
        
        data = request.get_json()
        
        if 'title' in data:
            note.title = data['title']
        if 'content' in data:
            note.content = data['content']
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'note': note.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


@bp.route('/<int:note_id>', methods=['DELETE'])
@jwt_required()
def delete_note(note_id):
    """删除笔记"""
    try:
        current_user_id = int(get_jwt_identity())
        note = Note.query.filter_by(id=note_id, user_id=current_user_id).first()
        
        if not note:
            return jsonify({'error': '笔记不存在'}), 404
        
        db.session.delete(note)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '笔记已删除'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

